#
# @file Makefile
# @Synopsis  
# @author xing.dai@aliyun.com
# @version 0.0.1
# @date 2018-07-27
#

# TOPDIR := $(shell pwd)
TOPDIR := $(abspath ./)
TARGET := test
export TOPDIR

include Makefile.rule
include Makefile.path



GIT_COMMIT_SHA1 := $(shell git log -n 1 | head -n 1 | cut -d ' ' -f 2)
DEF_MAKE += -DGIT_COMMIT_SHA1=\"$(GIT_COMMIT_SHA1)\"
DEF_MAKE += -DCOMPILER=\"$(CC)\"
CFLAGS 	+= $(DEF_MAKE) $(INC_PATH) $(ARCH_FLAGS)
ASFLAGS := $(INC_PATH) $(ARCH_FLAGS)
export CFLAGS LDFLAGS ARCH_FLAGS ASFLAGS

# Tmp target name
TARGET_DEBUG_NAME := test

#obj-y += filename.o
#obj-y += foldername/	# Need "/"

# Be silent per default, but 'make V=1' will show all compiler calls.
ifneq ($(V), 1)
Q := @
# Do not print "Entering directory ..."
MAKEFLAGS += --no-print-directory
endif
export Q

ifneq ($(TARGET),)
all: built-in elf bin hex list
else
all: no_target
endif
new: clean all
elf: $(TARGET).elf
bin: $(TARGET).bin
hex: $(TARGET).hex
list: $(TARGET).list

$(TARGET).bin: $(TARGET).elf
	$(Q)$(OBJCOPY) -Obinary $< $@

$(TARGET).hex: $(TARGET).elf
	$(Q)$(OBJCOPY) -Oihex $< $@

$(TARGET).list: $(TARGET).elf
	$(Q)$(OBJDUMP) -S $< > $@

$(TARGET).elf: built-in.o
	@printf "	Generate 	$@\n"
	$(Q)$(CC) $< -o $@ $(LDFLAGS)
	$(Q)$(SIZE) $@
	$(Q)cp $@ $(TARGET_DEBUG_NAME)

built-in:
	$(Q)$(MAKE) -C ./ -f $(TOPDIR)/Makefile.build

.PHONY: flash no_target style clean distclean realclean

# openocd script default path: /usr/share/openocd/scripts/
OPENOCD := openocd
OPENOCD_FLAGS := -f $(TOPDIR)/board/$(TARGET)/support/openocd.cfg
# OPENOCD_FLAGS += -s /usr/share/openocd/scripts

flash: $(TARGET).bin
	$(OPENOCD) $(OPENOCD_FLAGS) \
		-c init \
		-c targets \
		-c 'reset halt' \
		-c 'flash write_image erase $(TARGET).bin 0x08000000' \
		-c 'reset halt' \
		-c 'verify_image $(TARGET).bin 0x08000000' \
		-c 'reset run' \
		-c shutdown

debug: $(TARGET).elf
	$(GDB) -iex 'target extended | $(OPENOCD) $(OPENOCD_FLAGS) -c "gdb_port pipe"' \
		-iex 'monitor reset halt' -ex 'load' -ex 'break main' -ex 'c' $(TARGET).elf


no_target:
	$(Q)printf "No target, Please check .config file.\n"
	$(Q)printf "Usage: make xxx_defconfig\n"

style:
	$(Q)sh $(TOPDIR)/script/style_check.sh

# make linux_defconfig, make xxx_defconfig
%_defconfig:
	$(Q)$(MAKE) -f ./script/config/Makefile obj=./script/config $@

## RM = rm -f in makefile variables. Use $(RM) ... to remove files.
clean:
	$(Q)$(RM) $(shell find . -name "*.o")
	$(Q)$(RM) $(shell find . -name "*.tmp")
	$(Q)$(RM) $(shell find . -name "*.d")
	$(Q)$(RM) $(shell find . -name "*.bin")
	$(Q)$(RM) $(shell find . -name "*.hex")
	$(Q)$(RM) $(shell find . -name "*.list")
	$(Q)$(RM) $(shell find . -name "*.map")
	$(Q)$(RM) $(shell find . -name "*.elf")
	$(Q)$(RM) $(TARGET_DEBUG_NAME)

distclean: clean
	$(Q)$(RM) .config include/auto_config.h

realclean: distclean
	$(Q)$(RM) *.out tags *.taghl
